<template>
  <div class="gnb-add-note plr-md">
    <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
    >
      <el-form-item label="笔记名称" prop="name">
        <el-input v-model="form.name"
                  size="small"
                  autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="Git 地址" prop="gitAddress">
        <el-input v-model="form.gitAddress"
                  size="small"
                  autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label=" ">
        <div style="margin-top: 20px;" class="text-right">
          <el-button
              type="primary"
              icon="el-icon-circle-check"
              :loading="loading"
              @click="onClickAddButton"
          >保存笔记
          </el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import {reactive, ref, getCurrentInstance} from "vue";
import {IpcRenderer} from "@/utils/render/common";
import {PATTERN_FILE_NAME, validatePattern} from "@/utils/pattern.utils";


export default {
  name: 'gnb-add-note',
  mixins: [],
  components: {},
  props: {},
  data() {
    return {}
  },
  setup() {

    const instance = getCurrentInstance();

    // 表单
    const form = reactive({
      name: '',
      gitAddress: '',
    });

    const loading = ref(false);

    // 点击添加按钮
    const onClickAddButton = async () => {
      (instance.refs['formRef'] as { validate }).validate(async ok => {
        if (!ok) return;
        loading.value = true;
        const res = await IpcRenderer.invoke("addNote", {...form});
        loading.value = false;
        if( res ) instance.emit("on-add-success");
      })
    }

    // 表单规则
    const rules = {
      name: [
        {required: true, message: '笔记名称不能为空'},
        {
          validator: (rule, value, callback) => {
            const res = validatePattern(value, PATTERN_FILE_NAME);
            if (!res) return callback(new Error("笔记本名称不能含有 ? \\ * | “ < > : / 字符"))
            callback();
          }
        },
      ],
      gitAddress: [
        {required: true, message: 'Git 地址不能为空'},
        {
          validator: (rule, value: string, callback) => {
            if (!value.startsWith("http://") && !value.startsWith("https://")) {
              return callback(new Error("Git 地址必须为网络地址"))
            }
            callback();
          }
        }
      ]
    }

    return {
      form,
      onClickAddButton,
      loading,
      rules,
    }

  },
  computed: {},
  watch: {},
  created() {
  },
  mounted() {
  },
  beforeUnmount() {
  },
  activated() {
  },
  deactivated() {
  },
  methods: {}
};
</script>

<style scoped lang="less">
.gnb-add-note {

}
</style>